package com.iptv.grape.util;

import android.content.Context;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import androidx.annotation.RequiresApi;

import com.iptv.grape.RunTimeApplication;

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public class ScreenUtil {
    private static DisplayMetrics metrics;
    static{
        WindowManager windowManager = (WindowManager) RunTimeApplication.getCurApp().getSystemService(Context.WINDOW_SERVICE);
        if (windowManager==null){
            throw  new RuntimeException("WindowManager 获取失败");
        }else {
            metrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getRealMetrics(metrics);
        }
    }
    public static void getRealScreenRelatedInformation(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (windowManager != null) {
            DisplayMetrics outMetrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getRealMetrics(outMetrics);
            int widthPixels = outMetrics.widthPixels;
            int heightPixels = outMetrics.heightPixels;
            int densityDpi = outMetrics.densityDpi;
            float density = outMetrics.density;
            float scaledDensity = outMetrics.scaledDensity;
            //可用显示大小的绝对宽度（以像素为单位）。
            //可用显示大小的绝对高度（以像素为单位）。
            //屏幕密度表示为每英寸点数。
            //显示器的逻辑密度。
            //显示屏上显示的字体缩放系数。
//            (px to dp): dp = (int)(px / (displayMetrics.densityDpi / 160));
//            px = (int)(dp * (displayMetrics.densityDpi / 160));
        }
    }


    public static int getX(){
       if(metrics==null)
           return metrics.widthPixels;
       return 0;
    }

    public static int getXDp(){
        if(metrics==null)
            return  px2dp(metrics.widthPixels);
        return 0;
    }

    public static int getY(){
        if(metrics==null)
            return metrics.heightPixels;
        return 0;
    }

    public static int getYDp(){
        if(metrics==null)
            return  px2dp(metrics.widthPixels);
        return 0;
    }



    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(float dpValue) {
        final float scale = RunTimeApplication.getCurApp().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(float pxValue) {
        final float scale = RunTimeApplication.getCurApp().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}
